<template>
  <div
    v-loading="loading"
    class="dashboard-container"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="app-container">
      <!-- 组织架构内容 -->
      <el-card class="tree-card">
        <tree-tools
          :treeNode="company"
          :isRoot="true"
          @addDepts="addDepts"
        ></tree-tools>
        <el-tree
          :data="departs"
          :prop="defaultProps"
          :default-expand-all="true"
        >
          <tree-tools
            slot-scope="{ data }"
            :treeNode="data"
            @delDepts="getDepartments"
            @addDepts="addDepts"
            @editDepts="editDepts"
          ></tree-tools>
        </el-tree>
      </el-card>
    </div>
    <add-dept
      ref="addDept"
      :showDialog.sync="showDialog"
      :treeNode="node"
      @addDepts="getDepartments"
    ></add-dept>
  </div>
</template>

<script>
import TreeTools from "./components/tree-tools.vue";
import { getDepartments } from "@/api/departments";
import { tranListToTreeData } from "@/utils";
import AddDept from "./components/add-dept"; // 引入新增部门组件
export default {
  components: { TreeTools, AddDept },
  data() {
    return {
      departs: [
        {
          name: "总裁办",
          manager: "曹操",
          children: [{ name: "董事会", manager: "曹丕" }],
        },
        { name: "行政部", manager: "刘备" },
        { name: "人事部", manager: "孙权" },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
      company: {
        name: "江苏传智播客教育科技股份有限公司",
        manager: "负责人",
        id: "",
      },
      showDialog: false, // 控制 新增 窗体的显示与隐藏
      node: null, // 记录当前新增的点击节点
      loading: false, // 用来控制进度弹层的显示和隐藏
    };
  },
  created() {
    this.getDepartments(); // 调用自身的方法
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    clickScope(scope) {
      console.log(scope);
    },
    async getDepartments() {
      this.loading = true;
      const result = await getDepartments();
      this.company = { name: result.companyName, manager: "负责人" };
      // this.departs = result.depts; // 需要将其转化成树形结构
      this.departs = tranListToTreeData(result.depts, "");
      // 直接 打印 result 打印出来它是一个 扁平化的结构，并不是一个树形结构
      // 子结点的 pid ＝ 父节点的 id
      // 所有根节点的pid为空
      console.log(result);
      this.loading = false;
    },
    // 添加部门
    addDepts(node) {
      this.showDialog = true; // 显示弹层
      // 因为node是当前的点击的部门， 此时这个部门应该记录下来,
      this.node = node;
    },
    // 编辑
    editDepts(node) {
      // 首先打开弹层
      this.showDialog = true;
      this.node = node; // 赋值操作的节点
      this.$refs.addDept.getDepartDetail(node.id); // 直接调用子组件中的方法 传入一个id
    },
  },
};
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
